import {
    getPlayerData,
    storagePlayerData,
    ensureGroupAndPlayerExist,
    isPlayerExist

} from "../function/function.js";

export class ReleaseSlave extends plugin {
    constructor() {
        super({
            name: '[Sm]放生奴隶',
            dsc: '放生奴隶',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]放生(群友|奴隶)(\d+)?/, fnc: 'releaseSlave' }
            ]
        })
    }

    async releaseSlave(e) {
        if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 确保群组和玩家数据存在
        ensureGroupAndPlayerExist(ID[1], ID[0]);

        let slave = e.at;
        if (!slave) slave = e.msg.replace(/#|\/|放生|群友|奴隶|\s/g, '');
        slave = parseInt(slave);


        if (!isPlayerExist(ID[1], slave)) return e.reply(['该奴隶不存在']);

        const userData = await getPlayerData(ID[1], ID[0]);
        if (!userData.slave.includes(slave)) return e.reply(['你不是该奴隶的主人']);

        userData.slave = userData.slave.filter(id => id !== slave);
        storagePlayerData(ID[1], ID[0], userData);

        const slaveData = await getPlayerData(ID[1], slave);
        slaveData.master = '';
        storagePlayerData(ID[1], slave, slaveData);

        return e.reply([`成功放生了${slave}`]);
    }
}
